package com.fsd.admin.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.fsd.core.util.DateTimeUtil;
import com.fsd.core.util.PdfUtil;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Z_xkjnjs;
import com.fsd.admin.service.Z_xkjnjsService;
import com.fsd.admin.dao.Z_xkjnjsDao;

@Repository("z_xkjnjsServiceImpl")
public class Z_xkjnjsServiceImpl extends BaseServiceImpl<Z_xkjnjs, String> implements Z_xkjnjsService{
    
    private static final Logger log = Logger.getLogger(Z_xkjnjsServiceImpl.class);
    private String depict = "";
    
    @Resource(name = "z_xkjnjsDaoImpl")
	public void setBaseDao(Z_xkjnjsDao Z_xkjnjsDao) {
		super.setBaseDao(Z_xkjnjsDao);
	}
	
	@Resource(name = "z_xkjnjsDaoImpl")
	private Z_xkjnjsDao objectDao;

	@Autowired
	private RuntimeService activitiRuntimeService;

	@Autowired
	private IdentityService activitiIdentityService;

	@Autowired
	private RepositoryService activitiRepositoryService;
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
    @Override
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		if(!employee.isIsadmin()){
			if("true".equals(employee.getDepartmentadmin())){
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.eq("f_branchid", employee.getBranchid())));
				disjunction.add(Restrictions.or(Restrictions.eq("f_addemployeeid", employee.getId())));
				disjunction.add(Restrictions.or(Restrictions.eq("f_leaderid", employee.getId())));
				c.add(disjunction);
			}else{
				Disjunction disjunction = Restrictions.disjunction();
				disjunction.add(Restrictions.or(Restrictions.eq("f_addemployeeid", employee.getId())));
				disjunction.add(Restrictions.or(Restrictions.eq("f_leaderid", employee.getId())));
				c.add(disjunction);
			}
		}
		c.add(Restrictions.eq("f_deleted", "0"));
		c.addOrder(Order.asc("f_adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("f_name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}


	/**
	 * 保存学科技能竞赛基本信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_xkjnjs saveInfo(ParametersUtil param, Z_xkjnjs obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_xkjnjs old_obj = objectDao.get(obj.getId());
			old_obj.setF_gamename(obj.getF_gamename());
			old_obj.setF_profession(obj.getF_profession());
			old_obj.setF_gamelevelid(obj.getF_gamelevelid());
			old_obj.setF_gamelevelname(obj.getF_gamelevelname());
			old_obj.setF_gametypeid(obj.getF_gametypeid());
			old_obj.setF_gametypename(obj.getF_gametypename());
			old_obj.setF_hostunit(obj.getF_hostunit());
			old_obj.setF_undertaker(obj.getF_undertaker());
			old_obj.setF_jslyxx(obj.getF_jslyxx());
			old_obj.setF_formid(obj.getF_formid());
			old_obj.setF_formname(obj.getF_formname());
			old_obj.setF_gametime(obj.getF_gametime());
			old_obj.setF_site(obj.getF_site());
			old_obj.setF_basename(obj.getF_basename());
			old_obj.setF_baseleadername(obj.getF_baseleadername());
			old_obj.setF_applyformoney(obj.getF_applyformoney());
			old_obj.setF_matingmoney(obj.getF_matingmoney());
			old_obj.setF_matingmoneysource(obj.getF_matingmoneysource());
			old_obj.setF_group(obj.getF_group());
			old_obj.setF_people(obj.getF_people());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
			obj.setId(this.getUUID());
			obj.setF_adddate(this.getData());
			obj.setF_addemployeeid(employee.getId());
			obj.setF_branchid(employee.getBranchid());
			obj.setF_statusid("0");
			obj.setF_statusname("草稿");

			obj.setF_abstract("（主要包括竞赛项目的基本介绍，竞赛的目的和意义）");
			obj.setF_scheme("（主要包括竞赛宣传、参赛选手选拔、比赛内容、赛程赛制、奖项设置及预期目标等）");
			obj.setF_condition("");
			obj.setF_train("（指参加校外竞赛的培训管理、目标、计划、内容、方式、地点）");
			obj.setF_deleted("0");
			objectDao.save(obj);
			return obj;
		}
	}

	/**
	 * 保存学科技能竞赛负责人信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_xkjnjs saveLeader(ParametersUtil param, Z_xkjnjs obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_xkjnjs old_obj = objectDao.get(obj.getId());
			old_obj.setF_leaderid(obj.getF_leaderid());
			old_obj.setF_leadername(obj.getF_leadername());
			old_obj.setF_leaderphone(obj.getF_leaderphone());
			old_obj.setF_leadertitle(obj.getF_leadertitle());
			old_obj.setF_leaderbranch(obj.getF_leaderbranch());
			old_obj.setF_leaderresponsibility(obj.getF_leaderresponsibility());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存项目简介信息
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_xkjnjs saveAbstract(ParametersUtil param, Z_xkjnjs obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_xkjnjs old_obj = objectDao.get(obj.getId());
			old_obj.setF_abstract(obj.getF_abstract());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存实施方案及预期目标
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_xkjnjs saveScheme(ParametersUtil param, Z_xkjnjs obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_xkjnjs old_obj = objectDao.get(obj.getId());
			old_obj.setF_scheme(obj.getF_scheme());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存配套条件
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_xkjnjs saveCondition(ParametersUtil param, Z_xkjnjs obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_xkjnjs old_obj = objectDao.get(obj.getId());
			old_obj.setF_condition(obj.getF_condition());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}

	/**
	 * 保存培训方案
	 * @param param
	 * @param obj
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public Z_xkjnjs saveTrain(ParametersUtil param, Z_xkjnjs obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Z_xkjnjs old_obj = objectDao.get(obj.getId());
			old_obj.setF_train(obj.getF_train());
			objectDao.update(old_obj);
			return old_obj;
		}else{
			throw new BusinessException("系统错误，请联系管理员");
		}
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
    @Override
	public void save(String rootPath, ParametersUtil param, Z_xkjnjs obj, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		String status = objectMap.get("status").toString();
        if(obj.getId() != null && !"".equals(obj.getId())){
			File file = new File("uploadfiles/projectfile/" + obj.getId() + ".pdf");//删除PDF文件
			if(file.exists()) {
				file.delete();
			}

            //修改
            Z_xkjnjs old_obj = objectDao.get(obj.getId());
			if(status.equals("projectstate-cg")){
				obj.setF_statusid("0");
				obj.setF_statusname("草稿");
			}else if(status.equals("projectstate-tjwsh")){
				obj.setF_statusname("提交未审核");
				obj.setF_statusid("1");
			}

			old_obj.setF_name(obj.getF_name());
			old_obj.setF_gamename(obj.getF_gamename());
			old_obj.setF_gamelevelid(obj.getF_gamelevelid());
			old_obj.setF_gamelevelname(obj.getF_gamelevelname());
			old_obj.setF_gametypeid(obj.getF_gametypeid());
			old_obj.setF_gametypename(obj.getF_gametypename());
			old_obj.setF_hostunit(obj.getF_hostunit());
			old_obj.setF_undertaker(obj.getF_undertaker());
			old_obj.setF_profession(obj.getF_profession());
			old_obj.setF_formid(obj.getF_formid());
			old_obj.setF_formname(obj.getF_formname());
			old_obj.setF_gametime(obj.getF_gametime());
			old_obj.setF_site(obj.getF_site());
			old_obj.setF_basename(obj.getF_basename());
			old_obj.setF_baseleadername(obj.getF_baseleadername());
			old_obj.setF_applyformoney(obj.getF_applyformoney());
			old_obj.setF_matingmoney(obj.getF_matingmoney());
			old_obj.setF_matingmoneysource(obj.getF_matingmoneysource());
			old_obj.setF_group(obj.getF_group());
			old_obj.setF_people(obj.getF_people());
			old_obj.setF_leaderid(employee.getId());
			old_obj.setF_leadername(employee.getRealname());
			old_obj.setF_abstract(obj.getF_abstract());
			old_obj.setF_scheme(obj.getF_scheme());
			old_obj.setF_condition(obj.getF_condition());
			old_obj.setF_train(obj.getF_train());

            old_obj.setF_lastupdatedate(this.getData());//设置修改日期
			old_obj.setF_updateemployeeid(employee.getId());//设置修改用户id
			old_obj.setF_updateemployeename(employee.getRealname());//设置修改用户姓名
			doPdf(rootPath,old_obj);//生成修改后的PDF文件
            objectDao.update(old_obj);
        }else{
            //添加
			String code = "XKJNJS";
			DateTimeUtil dateTimeUtil = new DateTimeUtil();
			code = code + dateTimeUtil.getYear();
			int count = this.getTotalCount().intValue();
			code = code + (count + 1);

			if(status.equals("projectstate-cg")){
				obj.setF_statusid("0");
				obj.setF_statusname("草稿");
			}else if(status.equals("projectstate-tjwsh")){
				obj.setF_statusname("提交未审核");
				obj.setF_statusid("1");
			}

            obj.setId(this.getUUID());//设置主键
			obj.setF_code(code);
			obj.setF_leaderid(employee.getId());
			obj.setF_leadername(employee.getRealname());
			obj.setF_adddate(this.getData());//设置添加日期
			obj.setF_addemployeeid(employee.getId());//设置添加用户id
			obj.setF_addemployeename(employee.getRealname());//设置添加用户姓名
			obj.setF_deleted("0");//设置删除标志(0:正常 1：已删除)
			doPdf(rootPath,obj);
			objectDao.save(obj);
        }
    }

	/**
	 * 生成PDF文件
	 * @param rootpath
	 * @param obj
	 * @throws Exception
	 */
	private void doPdf(String rootpath, Z_xkjnjs obj) throws Exception {
		String pdfurl = "uploadfiles/projectfile/" + obj.getId() + ".pdf";
		obj.setF_pdfurl(pdfurl);
		//生成PDF文件
		String templatePath = rootpath + "uploadfiles/pdftemplate/xkjnjs_sb.pdf";
		String outPaht = rootpath + pdfurl;
		Map<String, Object> data = new HashMap<>();
		data.put("f_name", obj.getF_name());
		data.put("f_leadername", obj.getF_leadername());

		if(obj.getF_formid().equals("xkjnjsxs-tt")){
			data.put("f_formtt", "√");
		}else if(obj.getF_formid().equals("xkjnjsxs-gr")){
			data.put("f_formgr", "√");
		}
		data.put("f_adddate", DateTimeUtil.formatDate(obj.getF_adddate(), "yyyyMMddHHmmss", "yyyy年MM月dd日"));
		data.put("f_gamename", obj.getF_gamename());

		data.put("f_gamelevelname", obj.getF_gamelevelname());
		data.put("f_gametypename", obj.getF_gametypename());
		data.put("f_hostunit", obj.getF_hostunit());
		data.put("f_undertaker", obj.getF_undertaker());
		data.put("f_profession", obj.getF_profession());
		data.put("f_gametime", DateTimeUtil.formatDate(obj.getF_gametime(), "yyyyMMdd", "yyyy年MM月dd日"));
		data.put("f_site", obj.getF_site());
		data.put("f_basename", obj.getF_basename());
		data.put("f_baseleadername", obj.getF_baseleadername());
		data.put("f_applyformoney", obj.getF_applyformoney());
		data.put("f_matingmoney", obj.getF_matingmoney());
		data.put("f_matingmoneysource", obj.getF_matingmoneysource());
		data.put("f_group", obj.getF_group());
		data.put("f_people", obj.getF_people());
		data.put("f_abstract", obj.getF_abstract());
		data.put("f_scheme", obj.getF_scheme());
		data.put("f_condition", obj.getF_condition());
		data.put("f_train", obj.getF_train());
		PdfUtil.createPdfByTemplate(data, templatePath, outPaht);
	}

    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
    @Override
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		for (String id : dir) {
			Z_xkjnjs xkjnjs = objectDao.get(id);
			xkjnjs.setF_deleted("1");
			objectDao.update(xkjnjs);
		}
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
    @Override
	public Z_xkjnjs getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Z_xkjnjs obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		
		return obj;
	}

	/**
	 * 提交项目
	 * @param param
	 * @throws Exception
	 */
	@Override
	public void saveProjectSubmit(String rootpath, ParametersUtil param, A_Employee employee) throws Exception{
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("projectid") != null && !"".equals(objectMap.get("projectid")) && objectMap.get("type") != null && !"".equals(objectMap.get("type"))){
				String projectId = objectMap.get("projectid").toString();
				String type = objectMap.get("type").toString();
				Z_xkjnjs project = this.get(projectId);
				if("cg".equals(type)){
					project.setF_statusid("0");
					project.setF_statusname("草稿");
					this.update(project);
				}
				if("tj".equals(type)){
					project.setF_statusid("1");
					project.setF_statusname("提交待审核");
					this.update(project);
					startActiviti(project);
				}
			}else{
				throw new BusinessException("系统错误，请联系管理员");
			}
		}
	}

	/**
	 * 启动工作流
	 * @param obj
	 */
	public void startActiviti(Z_xkjnjs obj){
		String key = "xkjnjssblc";
		String objId = key+"."+ obj.getId();
		activitiIdentityService.setAuthenticatedUserId(obj.getF_leaderid());
		activitiRuntimeService.startProcessInstanceByKey(key,objId);
	}

	/**
	 * 根据项目ID加载项目当前审核节点信息
	 * @param projctId
	 * @return
	 * @throws Exception
	 */
	public String getProjectAuditStep(String projctId) throws Exception{
		String key = "xkjnjssblc";
		String objId = key+"."+ projctId;
		ProcessInstance instance = activitiRuntimeService.createProcessInstanceQuery().processInstanceBusinessKey(objId).singleResult();
		ProcessDefinitionEntity processDefinitionEntity=(ProcessDefinitionEntity) activitiRepositoryService.getProcessDefinition(instance.getProcessDefinitionId());
		ActivityImpl activityImpl = processDefinitionEntity.findActivity(instance.getActivityId()); // 根据活动id获取活动实例
		return activityImpl.getProperties().get("name").toString();
	}
}
